﻿<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="/lib/css/layout-default-latest.css" />
    <link rel="stylesheet" type="text/css" href="/lib/css/themes/base/jquery.ui.all.css" />
    <link href="/lib/css/StyleSheet1.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="/plugins/slick.grid.css" type="text/css" />
    <link rel="stylesheet" href="/lib/css/jquery.jdMenu.css" type="text/css" />
    <link href="/plugins/CheckList/ui.dropdownchecklist.themeroller.css" rel="stylesheet"
          type="text/css" />
    <style type="text/css">
        /* remove padding and scrolling from elements that contain an Accordion OR a content-div */
        .ui-layout-center, /* has content-div */ .ui-layout-west, /* has Accordion */ .ui-layout-east, /* has content-div ... */ .ui-layout-east .ui-layout-content {
            /* content-div has Accordion */
            padding: 0;
            overflow: hidden;
        }

            .ui-layout-center P.ui-layout-content {
                line-height: 1.4em;
                margin: 0; /* remove top/bottom margins from <P> used as content-div */
            }

        h3, h4 {
            /* Headers & Footer in Center & East panes */
            font-size: 1.1em;
            background: #EEF;
            border: 1px solid #BBB;
            border-width: 0 0 1px;
            padding: 7px 10px;
            margin: 0;
        }

        .ui-layout-east h4 {
            /* Footer in East-pane */
            font-size: 0.9em;
            font-weight: normal;
            border-width: 1px 0 0;
        }

        .menuContainerJSListBox {
            margin-left: 50px;
            margin-right: 50px;
            overflow: scroll;
        }

        .DCTextClass {
            margin-top: 10px;
            margin-left: 50px;
            margin-right: 50px;
            margin-bottom: 20px;
        }

        .NDPriceCss {
        }

        .highlightPriceApporver {
            background-color: white;
            border: 1px solid black;
        }

        .highlightPriceApporver1 {
            background-color: #1bbe46;
            height: 23px;
        }

        .highlightPriceApporver2 {
            background-color: Orange;
            height: 23px;
        }

        .highlightPriceApporver3 {
            background-color: #FF3300;
            height: 23px;
        }

        #loadingScreen {
            background: url(../images/ajax-loader.gif) no-repeat 5px 8px;
            padding-left: 25px;
        }

        .inputDisable {
            background: grey;
        }

        .panel {
            background: url("/images/panel_bg.gif") repeat-x scroll center top transparent;
            border: 0 none;
            display: block;
            font-size: 100%;
            margin: 0 auto;
            padding: 0;
            position: relative;
            width: 17em;
            margin-top: 50px;
        }

        .panelstatus {
            font-size: 100%;
            margin: 0 auto;
            width: 17em;
        }

        .panel .boxhead {
            background: url("/images/panel_boxhead_bg.gif") no-repeat scroll left top transparent;
            border: 0 none;
            display: block;
            margin: 0;
            padding: 0;
            position: relative;
            text-align: center;
            width: auto;
        }

            .panel .boxhead h2, .panel .boxfooter h2 {
                background: url("/images/panel_boxhead_h2_bg.gif") no-repeat scroll right top transparent;
                color: #378080;
                display: block;
                font-family: "Trebuchet MS",verdana,arial;
                font-size: 10px;
                font-weight: bold;
                height: 14px;
                margin: 0;
                padding: 3px 0 1px 10px;
                text-align: left;
                width: auto;
            }

        .panel .boxbody {
            background: url("/images/panel_boxfooter_bg.gif") repeat-y scroll left bottom #FFFFFF;
            border-right: 1px solid #CAC9C9;
            border-top: 1px solid #CAC9C9;
            margin: 0;
            padding: 0;
            position: relative;
        }

        .panel .boxfooter {
            background: url("/images/panel_boxfooter_bg.gif") repeat-x scroll 11px 11px #FFFFFF;
            height: 12px;
            margin: 0;
            padding: 0;
        }

            .panel .boxfooter .statusBar {
                background: url("/images/panel_boxfooter_statusBar_bg.gif") no-repeat scroll left top transparent;
                height: 12px;
                margin: 0;
            }

                .panel .boxfooter .statusBar h2 {
                    background: url("/images/panel_boxfooter_statusBar_h2_bg.gif") no-repeat scroll right top transparent;
                    display: block;
                    height: 12px;
                    margin: 0;
                    padding: 0;
                }

        .panelstatus .boxfooter {
            color: #999999;
            font-size: 9px;
            height: 15px;
            margin: 0;
            padding: 5px 0 8px 15px;
        }

        .panel .content {
            margin: 0;
            padding: 0 10px;
            position: relative;
            width: auto !important;
        }

            .panel .content .innerContent {
                margin: 0;
                padding: 0;
                width: 100%;
            }

        #treeWindow .innerContent {
            height: 100%;
        }

        .panel .menubar_panel {
            background-image: url("/umbraco_client/tabView/images/background.gif");
            border-bottom: 1px solid #CAC9C9;
            border-left: 1px solid #CAC9C9;
            border-right: 1px solid #CAC9C9 !important;
            display: block;
            height: 32px;
            margin: 0;
            overflow: hidden;
            padding: 0;
        }
    </style>
    <!-- REQUIRED scripts for layout widget -->
    <script src="/lib/js/jquery-latest.js" type="text/javascript"></script>
    <script src="/lib/js/jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="/lib/js/jquery.layout-latest.js"></script>
    <script type="text/javascript" src="/lib/js/jquery.layout.resizePaneAccordions-1.0.js"></script>
    <script src="/Scripts/CurrentTime.js" type="text/javascript"></script>
    <script src="/plugins/globalize.js" type="text/javascript"></script>
    <script type="text/javascript" src="/lib/js/themeswitchertool.js"></script>
    <script type="text/javascript" src="/lib/js/debug.js"></script>
    <script type="text/javascript" src="/lib/js/jquery.dimensions.js"></script>
    <script type="text/javascript" src="/lib/js/jquery.positionBy.js"></script>
    <script type="text/javascript" src="/lib/js/jquery.bgiframe.js"></script>
    <script type="text/javascript" src="/lib/js/jquery.jdMenu.js"></script>
    <script src="/lib/js/jquery.event.drag-2.0.min.js"></script>
    <script src="/plugins/slick.editors.js"></script>
    <script src="/plugins/slick.core.js"></script>
    <script src="/plugins/slick.checkboxselectcolumn.js"></script>
    <script src="/plugins/slick.autotooltips.js"></script>
    <script src="/plugins/slick.cellrangedecorator.js"></script>
    <script src="/plugins/slick.cellrangeselector.js"></script>
    <script src="/plugins/slick.cellcopymanager.js"></script>
    <script src="/plugins/slick.cellselectionmodel.js"></script>
    <script src="/plugins/slick.rowselectionmodel.js"></script>
    <script src="/plugins/slick.formatters.js"></script>
    <script src="/plugins/slick.grid.js"></script>
    <script src="/Scripts/Helper.js" type="text/javascript"></script>
    <script src="/plugins/surge.core.js" type="text/javascript"></script>
    <script src="/plugins/surge.slickGrid.js" type="text/javascript"></script>
    <script src="/plugins/ListView/js-inherit.js" type="text/javascript"></script>
    <script src="/plugins/ListView/js-listbox.js" type="text/javascript"></script>
    <script src="/plugins/CheckList/ui.dropdownchecklist.js" type="text/javascript"></script>
    <script src="/Scripts/AjaxLoading.js" type="text/javascript"></script>
    <script src="/Scripts/validation.js" type="text/javascript"></script>
    <script type="text/javascript">
        window.onload = DisplayTime;
        function stopRKey(evt) {
            var evt = (evt) ? evt : ((event) ? event : null);
            var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
            if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
        }

        document.onkeypress = stopRKey;
        var myLayout;
        var mysupLayout;
        var approverAll = [];
        $(document).ready(function () {
            var rolename = $.cookie("userrole");
            if (rolename == null || rolename.toLowerCase() != 'saleco') {
                window.location = '/Page/login.aspx';
            }


            //loadFrm("/page/userManagement.htm");

            myLayout = $('body').layout({
                west__size: 234,
                east__size: 300
                // RESIZE Accordion widget when panes resize
                ,
                west__onresize: $.layout.callbacks.resizePaneAccordions,
                east__onresize: $.layout.callbacks.resizePaneAccordions
            });

            //            mysupLayout = $('#mainFrame').layout({
            //                center__paneSelector:	".inner-center"
            //                , west__paneSelector:		".inner-west"
            //                ,west__size: '40%'
            //                ,south__size:'50%'
            //                });

            $('ul.dropdown').jdMenu();
            // ACCORDION - in the West pane
            $("#accordion1").accordion({ fillSpace: true });

            // ACCORDION - in the East pane - in a 'content-div'
            $("#accordion2").accordion({
                fillSpace: true,
                active: 1
            });


            // THEME SWITCHER
            addThemeSwitcher('.ui-layout-north', { top: '12px', right: '5px' });
            // if a new theme is applied, it could change the height of some content,
            // so call resizeAll to 'correct' any header/footer heights affected
            // NOTE: this is only necessary because we are changing CSS *AFTER LOADING* using themeSwitcher
            setTimeout(myLayout.resizeAll, 1000); /* allow time for browser to re-render with new theme */
            $(".toolbarCommand button:first").button({
                icons: {
                    primary: "ui-icon-plusthick"
                },

            }).next().button({
                icons: {
                    primary: "ui-icon-gear"
                }
            }).next().button({
                icons: {
                    primary: "ui-icon-minusthick"
                }
            });

            $("#dialog-message").dialog({
                autoOpen: false,
                resizable: false,
                height: 120,
                dialogClass: "Dialog",
                modal: true,
                buttons: {
                    Ok: function () {
                        $(this).dialog("close");
                    }
                }
            });

            $("#DivNdpriceDetails").dialog({
                autoOpen: false,
                resizable: false,
                title: "ND Price",
                width: 500,
                dialogClass: "Dialog",
                modal: true,
                buttons: {
                    Ok: function () {
                        $(this).dialog("close");
                    }
                }
            });
            if ($.cookie("saleID") == null) {
                showLayout('0');
            } else if ($.cookie("apptype") === "01" || $.cookie("apptype") === "02") {
                showLayout('1');


            } else {
                showLayout('0.1');

            }
            //showLayout('0');
            $("#bthQuickSearchDoc").button({
                icons: {
                    primary: "ui-icon-search"
                }
            })
                .click(function () {
                    searchDocument();
                });
            helper.GetAllApproveLevel(function (approval) {
                approverAll = approval;
                $.each(approverAll.AllApprover, function (i, v) {
                    if (i == 0) {
                        $('head').append("<style>.highlightPriceApporve { background-color:" + v.warningColor + " }</style>");
                        $('#approvalDisplay').text(v.approveDisplay);
                    }
                    else if (i == 3) {
                        $('#approvalDisplay' + i).text(v.approveDisplay);
                    } else {
                        $('head').append("<style>.highlightPriceApporver" + i + " { background-color:" + v.warningColor + " }</style>");
                        $('#approvalDisplay' + i).text(v.approveDisplay);
                    }


                });
            });
        });
        function loadControl(url, divTarget) {

            $.get(url, function (content) {

                $('#' + divTarget).html(content);

            });
        }
        function SelectApplication() {
            if ($('input[id=RadioCustomer]:radio:checked').val() == 'on') {
                $.cookie("apptype", '01', { path: '/' });
            }
            if ($('input[id=RadioPriceGroup]:radio:checked').val() == 'on') {
                $.cookie("apptype", '02', { path: '/' });
            }
            showLayout('1');
        }
        function GridDocumentInit(gridtarget, allDocument, status) {
            var columnGridDocument = [
                    { id: "StatusDescription", name: "สถานะ", field: "StatusDescription", width: 120, cssClass: "cell-title" },
                    { id: "DocID", name: "Document ID", field: "DocID", width: 120 },
                { id: "Region", name: "Region", field: "Region" },
                { id: "CreateBy", name: "CreateBy", field: "UserName", width: 80, resizable: false },
                { id: "CreateOn", name: "CreateOn", field: "Created", minWidth: 60 },
                { id: "Enter", name: "", field: "DocID", formatter: Slick.Formatters.Enter }
            ];
            var optionsDocumentGrid = {
                editable: true,
                enableRowReordering: true,
                enableCellNavigation: true,
                asyncEditorLoading: false,
                autoEdit: true
            };
            var documentgrid;
            var datas = [];
            if (status === 'all') {
                datas = allDocument;
                documentgrid = new Slick.Grid(gridtarget, datas, columnGridDocument, optionsDocumentGrid);
                documentgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
                documentgrid.onCellChange.subscribe(function (e, args) {
                    //updateUser(args.item);
                });
            }
            else if (status === '51') {
                datas = jQuery.grep(allDocument, function (n, i) {
                    return (n.isedited === true);
                });
                documentgrid = new Slick.Grid(gridtarget, datas, columnGridDocument, optionsDocumentGrid);
                documentgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
                documentgrid.onCellChange.subscribe(function (e, args) {
                    //updateUser(args.item);
                });
            }
            else if (status === '99') {
                helper.getAllNdPrice(function (allNdPrice) {
                    datas = allNdPrice.RNdPrice;
                    var columnGridNdPrice = [
                        { id: "NDRound", name: "ID", field: "NDRound", width: 120, cssClass: "cell-title" },
                        { id: "ValidON", name: "ValidON", field: "ValidON" },
                        { id: "ValidTO", name: "ValidTO", field: "ValidTO", width: 80 },
                        { id: "remark", name: "remark", field: "remark", minWidth: 60 },

                        { id: "ShowNDPrice", name: "", field: "NDRound", formatter: Slick.Formatters.ShowNDPrice }
                    ];
                    documentgrid = new Slick.Grid(gridtarget, datas, columnGridNdPrice, optionsDocumentGrid);
                    documentgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
                    documentgrid.onCellChange.subscribe(function (e, args) {
                        //updateUser(args.item);
                    });
                });

            }
            else {
                datas = jQuery.grep(allDocument, function (n, i) {
                    return (n.Status === status);
                });
                documentgrid = new Slick.Grid(gridtarget, datas, columnGridDocument, optionsDocumentGrid);
                documentgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
                documentgrid.onCellChange.subscribe(function (e, args) {
                    //updateUser(args.item);
                });
            }
            documentgrids[status] = documentgrid;
            //            var columns = createColumnGrid();
            //            ProdData('insert', getProductSelect());
            //            var datas = productGridData;
            //            productgrid = new Slick.Grid(gridtarget, datas , columns, optionsProductGrid);
            //            productgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
            //            productgrid.onCellChange.subscribe(function (e, args) {
            //                //updateUser(args.item);
            //            });
        }

        function initStep2(parameters) {
            mysupLayout = $('#mainFrame').layout({
                center__paneSelector: ".inner-center"
              , west__paneSelector: ".inner-west"
              , west__size: '40%'
              , south__size: '30%'
            });
        }
        var isneednewID = false;
        var draftDocID = "";
        var allDocs;
        var allTab;
        var documentgrids = {};
        function showLayout(step, docid, doctype, isdraft, neednewID) {
            switch (step) {
                case '0':
                    $('#mainFrame').html($('#SelectSaleDiv').html());

                    SaleInit();

                    $("#btnSelectSale")
                           .button({

                               icons: {
                                   primary: "ui-icon-circle-check"
                               },
                           })
                           .click(function () {
                               if (saleID === '' || saleID === undefined) {
                                   var top = ($(window).height() - 250) / 2;
                                   var left = ($(window).width() - 350) / 2;
                                   var message = 'Please select sale.';

                                   $('#dialogMessageID').text(message);
                                   $("#dialog-message").dialog("open");
                                   $(".Dialog").css('left', left);
                                   $(".Dialog").css('top', top);
                               }
                               else {
                                   $.cookie("saleID", saleID, { path: '/' });
                                   helper.SetCurrentUserDetail(saleID, function (data) {
                                       showLayout('0.1');
                                       loadControl("/Control/CompletedDocumentControl.htm", "completedDocument");
                                   });
                               }

                           });

                    $("#btnSearchSale").button({

                        icons: {
                            primary: "ui-icon-search"
                        }
                    })
                    .click(function () {
                        searchSale();
                    });
                    break;
                case '0.1':
                    $('#mainFrame').html($('#docTypeSelect').html());
                    $("#btnNext")
                            .button({

                                icons: {
                                    primary: "ui-icon-circle-check"
                                },
                            })
                            .click(function () {
                                SelectApplication();

                            });
                    $("#btnBackToSelectSale")
                           .button({

                               icons: {
                                   primary: "ui-icon-circle-arrow-w"
                               },
                           })
                           .click(function () {
                               $.cookie("saleID", null, { path: '/' });
                               showLayout('0');
                           });


                    break;
                case '1':
                    $('#mainFrame').html($('#DocumentManageStep').html());
                    loadControl("/Control/CompletedDocumentControl.htm", "completedDocument");
                    buttonInit();
                    var tabHtmlComplete = '';
                    var divHtmlComplate = '';
                    var tabItemHtml = '<ul>{0}<ul>';
                    var tabItemComplete = '';
                    var constTabID = 'tab';
                    var constGrid = 'grid';
                    var constAllstatus = 'all';
                    helper.GetStatusTab(function (allTabStatus) {
                        allTab = allTabStatus.AllStatus;
                        var htmltemplate = '<li><a href="#{0}">{1}</a></li>';
                        tabItemComplete += htmltemplate.format(constTabID + constAllstatus, 'ALL'); // add tab All
                        $.each(allTabStatus.AllStatus, function (key, value) {
                            tabItemComplete += htmltemplate.format(constTabID + value.StatusID, value.StatusDescription);

                        });
                        tabHtmlComplete = tabItemHtml.format(tabItemComplete);
                        var divTemplate = '<div id="{0}"><div></div><div style="height:350px;" id="{1}">{0}</div></div>';
                        divHtmlComplate += divTemplate.format(constTabID + constAllstatus, constGrid + constAllstatus); // add div grid all
                        $.each(allTabStatus.AllStatus, function (key, value) {
                            divHtmlComplate += divTemplate.format(constTabID + value.StatusID, constGrid + value.StatusID);

                        });

                        $("#tabs").html(tabHtmlComplete).append(divHtmlComplate);

                        helper.GetAllDocumentByUser($.cookie("apptype"), function (alldocument) {
                            allDocs = alldocument.AllDocument;
                            GridDocumentInit('#' + constGrid + constAllstatus, alldocument.AllDocument, constAllstatus);
                            $.each(allTabStatus.AllStatus, function (key, value) {
                                GridDocumentInit('#' + constGrid + value.StatusID, alldocument.AllDocument, value.StatusID);
                            });
                            //GridDocumentInit('#grid11' ,alldocument.AllDocument,'11');
                        });



                        $("#tabs").tabs({ selected: 6 });
                    });
                    break;

                case '2':
                    $('#mainFrame').html($('#customerProductStep').html());
                    initStep2();
                    CustomerProductiMappingInit();
                    break;

                case '3':
                    $('#mainFrame').html($('#gridproductDetailStep').html());
                    isneednewID = neednewID;
                    var _docytype = '';
                    if (doctype) {
                        _docytype = doctype;
                    }
                    else {
                        _docytype = $.cookie("apptype");
                    }

                    $("#btnAddPrice").button({

                        icons: {
                            //                    primary: "ui-iconui-icon-plus"
                        }
                    })
                    .click(function () {

                        if (isNumber($('#txtaddPrice').val()) && $('#txtaddPrice').val() != '') {
                            chageAllPrice(true, parseInt($('#txtaddPrice').val()));
                        }
                        else {
                            MsgBox('Please enter correct number');
                        }
                    });

                    //                $("#btnMinusPrice").button({
                    //
                    //                icons: {
                    //                    primary: "ui-icon-minus"
                    //                }
                    //                })
                    //			    .click(function () {
                    //
                    //			            chageAllPrice(false, $('#txtMinusPrice').val());
                    //			    });

                    $("#btnBackToDocList").button({

                        icons: {
                            primary: "ui-icon-circle-arrow-w"
                        }
                    })
                    .click(function () {

                        window.location.reload(true);
                    });

                    $("#btnExit2").button({

                        icons: {
                            primary: "ui-icon-circle-arrow-n"
                        }
                    })
                   .click(function () {
                       exitToFirstPage();
                   });

                    //                $("#btnBackToSelectDoctype").button({
                    //
                    //                icons: {
                    //                    primary: "ui-icon-circle-arrow-w"
                    //                }
                    //                })
                    //			    .click(function () {
                    //			        $.cookie("apptype", '');
                    //			        window.location.reload(true);
                    //			    });
                    $("#btnSaveTodraft").button({

                        icons: {
                            primary: "ui-icon-document"
                        }
                    })
                    .click(function () {
                        if (validateBlankCell() == true) {
                            var k = discountgrid.getData();
                            var needPopup = jQuery.grep(k, function (o) {
                                return o.ProdID == 53 || o.ProductDesc == "สายยางอ่อน-ใส";
                            });

                            if (needPopup.length > 0) {
                                $("#dialog-creditTerm").dialog({
                                    autoOpen: false,
                                    resizable: false,
                                    height: 180,
                                    dialogClass: "Dialog",
                                    modal: true,
                                    buttons: {
                                        Save: function () {
                                            //alert($("input[name='groupCreditTerm']:checked").val());
                                            saveDocument(_docytype, '30', $("input[name='groupCreditTerm']:checked").val());
                                            $(this).dialog("close");
                                        }
                                    }
                                });
                                var top = ($(window).height() - 250) / 2;
                                var left = ($(window).width() - 350) / 2;
                                $("#dialog-creditTerm").dialog("open");
                                $(".Dialog").css('left', left);
                                $(".Dialog").css('top', top);

                            } else {
                                saveDocument(_docytype, '30');
                            }
                        }
                    });
                    $("#btnSendToApproval")
                     .button({

                         icons: {
                             primary: "ui-icon-mail-closed"
                         }
                     })
                     .click(function () {

                         var valid = true;
                         var validon = $.datepicker.formatDate('yy-mm-dd', $('#txtValidOn').datepicker('getDate'));

                         var validto = $.datepicker.formatDate('yy-mm-dd', $('#txtValidTo').datepicker('getDate'));

                         valid = valid && IsNull(validon);
                         valid = valid && IsNull(validto);
                         var message = 'Please select Valid ON and Valid To date.';
                         var tomorrow = new Date();
                         tomorrow.setHours(0, 0, 0, 0);
                         if ($('#txtValidOn').datepicker('getDate') < tomorrow) {
                             message = "วันที่เริ่มต้นต้องเป็นวันที่ปัจจุบันหรือวันที่ในอนาคต.";
                             valid = false;
                         }
                         if ($('#txtValidTo').datepicker('getDate') < $('#txtValidOn').datepicker('getDate')) {
                             message = "วันที่สิ้นสุดต้องมากกว่าหรือเท่ากับวันที่เริ่มต้น.";
                             valid = false;
                         }
                         if (valid) {
                             if (validateBlankCell() == true) {
                                 var k = discountgrid.getData();
                                 var needPopup = jQuery.grep(k, function (o) {
                                     return o.ProdID == 53 || o.ProductDesc == "สายยางอ่อน-ใส";
                                 });

                                 if (needPopup.length > 0) {
                                     $("#dialog-creditTerm").dialog({
                                         autoOpen: false,
                                         resizable: false,
                                         height: 180,
                                         dialogClass: "Dialog",
                                         modal: true,
                                         buttons: {
                                             Save: function () {
                                                 //alert($("input[name='groupCreditTerm']:checked").val());
                                                 saveDocument(_docytype, '11', $("input[name='groupCreditTerm']:checked").val());
                                                 $(this).dialog("close");
                                             }
                                         }
                                     });
                                     var top = ($(window).height() - 250) / 2;
                                     var left = ($(window).width() - 350) / 2;
                                     $("#dialog-creditTerm").dialog("open");
                                     $(".Dialog").css('left', left);
                                     $(".Dialog").css('top', top);

                                 } else {
                                     saveDocument(_docytype, '11');
                                 }
                             }
                         }
                         else {
                             var top = ($(window).height() - 250) / 2;
                             var left = ($(window).width() - 350) / 2;
                             $('#dialogMessageID').text(message);
                             $("#dialog-message").dialog("open");
                             $(".Dialog").css('left', left);
                             $(".Dialog").css('top', top);
                         }
                     });

                    if (docid) {
                        var optionsProductGrid = {
                            editable: true,
                            enableRowReordering: true,
                            enableCellNavigation: true,
                            asyncEditorLoading: false,
                            autoEdit: true
                        };
                        $("#txtDocID").text(docid);
                        if (isdraft) {
                            draftDocID = docid;
                            //$('#btnSaveTodraft').hide();
                            helper.GetColumnDocumentDetailByDocID(docid, _docytype, function (columns) {
                                var csDraft = [];
                                csDraft.push({ id: "ProductDesc", name: "", field: "ProductDesc", minWidth: 60 });
                                csDraft.push({ id: "NDPrice", name: "NDPrice", field: "NDPrice", minWidth: 60, cssClass: 'NDPriceCss' });
                                var columnSelection = [];
                                $.each(columns.allColumns, function (key, value) {
                                    if (value.ParentText != undefined && value.ParentText != 'null') {
                                        csDraft.push({ parentable: 1, dc: value.DCID, id: value.RefID, name: '(DC ' + value.DCID + ') ' + value.mcustname1 + "(" + value.ParentText + ")", field: value.RefID, minWidth: 60, width: 150, formatter: Slick.Formatters.DisableSupport, editor: Slick.Editors.Price, toolTip: value.ParentText });
                                    }
                                    else {
                                        csDraft.push({ parentable: 1, dc: value.DCID, id: value.RefID, name: '(DC ' + value.DCID + ') ' + value.mcustname1, field: value.RefID, minWidth: 60, width: 150, formatter: Slick.Formatters.DisableSupport, editor: Slick.Editors.Price, toolTip: value.ParentText });
                                    }
                                    columnSelection.push(value.RefID);
                                });



                                helper.GetDocumentDetailByDocID(docid, true, function (datas) {
                                    var dDraft = [];

                                    helper.GetProductToSale(function (data) {
                                        var products = data.AllProduct;
                                        $.each(products, function (key, value) {
                                            var isAlreadyAdded = false;
                                            $.each(datas.AllDocumentDetail, function (key2, value2) {
                                                if (value2.ProductDesc === value.mprodh_grpname) {
                                                    var prodItem = value2;
                                                    prodItem.NDPriceApprove1 = value.NDApproverLevel1;
                                                    prodItem.NDPriceApprove2 = value.NDApproverLevel2;
                                                    prodItem.NDPriceApprove3 = value.NDApproverLevel3;
                                                    dDraft.push(value2);
                                                    isAlreadyAdded = true;

                                                }
                                                //                                                else {
                                                //                                                    dDraft.push('N/A');
                                                //                                                }
                                            });
                                            if (isAlreadyAdded == false) {
                                                dDraft.push({ ProductDesc: value.mprodh_grpname, NDPrice: value.discountPrice });
                                            }
                                        });
                                    });
                                    $(dDraft).each(function (k, v) {
                                        for (var i = 0; i < columns.allColumns.length; i++) {
                                            if (v[columns.allColumns[i].RefID] == undefined) {
                                                v[columns.allColumns[i].RefID] = 'N/A';
                                            }
                                        }
                                    });
                                    RefreshGridDiscount(dDraft, csDraft, optionsProductGrid, columnSelection);

                                });
                            });
                            var docdetail;
                            if (allDocs != undefined) {
                                var docdetailsDraft = jQuery.grep(allDocs, function (n, i) {
                                    return (n.DocID === docid);
                                });
                                docdetail = docdetailsDraft[0];
                            }
                            $('#txtValidOn').attr('readonly', 'readonly');
                            $('#txtValidTo').attr('readonly', 'readonly');
                            if (isneednewID == true) {
                                $("#txtValidOn").datepicker({ dateFormat: 'yy-mm-dd', minDate: new Date(), showOn: "button", buttonImage: "/images/calendar.gif", buttonImageOnly: true });
                                $("#txtValidTo").datepicker({ dateFormat: 'yy-mm-dd', minDate: new Date(), showOn: "button", buttonImage: "/images/calendar.gif", buttonImageOnly: true });
                            }
                            else {
                                //$("#txtValidOn").datepicker({ dateFormat: 'yy-mm-dd', minDate: TimeStampToDate(docdetail.ValidON), showOn: "button", buttonImage: "/images/calendar.gif", buttonImageOnly: true });
                                $("#txtValidOn").datepicker({ dateFormat: 'yy-mm-dd', minDate: new Date(), showOn: "button", buttonImage: "/images/calendar.gif", buttonImageOnly: true });
                                $("#txtValidTo").datepicker({ dateFormat: 'yy-mm-dd', minDate: new Date(), showOn: "button", buttonImage: "/images/calendar.gif", buttonImageOnly: true });
                                $('#txtValidOn').datepicker("setDate", TimeStampToDate(docdetail.ValidON));
                                $('#txtValidTo').datepicker("setDate", TimeStampToDate(docdetail.ValidTO));
                                $('#remark').val(docdetail.Remark);
                                $('#remark2').val(docdetail.Remark2);
                            }

                            $("#txtValidOn").change(function () {
                                var test = $(this).datepicker('getDate');
                                $("#txtValidTo").datepicker("option", "minDate", test);
                            });


                        }
                        else {

                            var optionsProductGridReadOnly = {
                                editable: false,
                                enableRowReordering: true,
                                enableCellNavigation: true,
                                asyncEditorLoading: false,
                                autoEdit: false
                            };
                            $("#SpanAddPrice").hide();
                            //Init Print button only status uploaded to sap



                            helper.GetColumnDocumentDetailByDocID(docid, _docytype, function (columns) {
                                var cs = [];
                                cs.push({ id: "ProductDesc", name: "", field: "ProductDesc", minWidth: 60 });
                                cs.push({ id: "NDPrice", name: "NDPrice", field: "NDPrice", minWidth: 60, cssClass: 'NDPriceCss' });

                                $.each(columns.allColumns, function (key, value) {
                                    if (value.ParentText != undefined && value.ParentText != 'null') {
                                        cs.push({ parentable: 1, id: value.RefID, name: '(DC ' + value.DCID + ') ' + value.mcustname1 + "(" + value.ParentText + ")", dc: value.DCID, field: value.RefID, minWidth: 60, width: 150, formatter: Slick.Formatters.DisableSupport, toolTip: value.ParentText });
                                    }
                                    else {
                                        cs.push({ parentable: 1, id: value.RefID, name: '(DC ' + value.DCID + ') ' + value.mcustname1, dc: value.DCID, field: value.RefID, minWidth: 60, width: 150, formatter: Slick.Formatters.DisableSupport, toolTip: value.ParentText });
                                    }
                                });

                                helper.GetDocumentDetailByDocID(docid, false, function (datas) {
                                    var d = [];
                                    helper.GetProductToSaleDocid(docid, function (data) {
                                        $.each(data.AllProduct, function (key, value) {
                                            $.each(datas.AllDocumentDetail, function (key2, value2) {
                                                var item = value2;
                                                if (value.mprodh_grpname === value2.ProductDesc) {
                                                    item.NDPriceApprove1 = value.NDApproverLevel1;
                                                    item.NDPriceApprove2 = value.NDApproverLevel2;
                                                    item.NDPriceApprove3 = value.NDApproverLevel3;
                                                    d.push(item);
                                                }

                                            });
                                        });
                                    });

                                    //sortJsonArrayByProp(d, "sort")();
                                    RefreshGridDiscount(d, cs, optionsProductGridReadOnly);

                                    //discountgrid = new Slick.Grid("#SaleCustomerDetailGrid", d, cs, optionsProductGridReadOnly);
                                    //discountgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));


                                });
                            });
                            $('#divSendToApprover').hide();
                            var docdetails = jQuery.grep(allDocs, function (n, i) {
                                return (n.DocID === docid);
                            });

                            var docdetail = docdetails[0];
                            //$("#txtValidOn").datepicker("option", "minDate", '' );
                            $('#txtValidOn').val(TimeStampToDate(docdetail.ValidON));
                            $('#txtValidTo').val(TimeStampToDate(docdetail.ValidTO));
                            $('#txtValidOn').attr('readonly', 'readonly');
                            $('#txtValidTo').attr('readonly', 'readonly');
                            $('#remark').val(docdetail.Remark);
                            $('#remark2').val(docdetail.Remark2);
                            $('#remark').attr("disabled", true);
                            $('#remark').attr("class", 'inputDisable');
                            $('#remark2').attr("disabled", true);
                            $('#remark2').attr("class", 'inputDisable');
                        }
                        //Init Print button
                        //$("#btnPrint").show();
                        $("#btnPrint")
                        .button({

                            icons: {
                                primary: "ui-icon-plus"
                            }
                        })
                        .click(function () {
                            window.open('/Page/ReportViewer.aspx?sale=true&docid=' + docid + '&doctype=' + doctype);

                        });
                        var data = jQuery.grep(allDocs, function (n, i) {
                            return (n.DocID === docid);
                        });
                        if (data.length > 0) {
                            var printStatus = ["10", "11", "20", "30", "40", "50"];
                            if (jQuery.inArray(data[0].Status, printStatus) != -1) {
                                $("#btnPrint").show();

                            }
                        }
                    }
                    else {
                        var optionsProductGrid = {
                            editable: true,
                            enableRowReordering: true,
                            enableCellNavigation: true,
                            asyncEditorLoading: false,
                            autoEdit: true
                        };
                        //$("#SpanAddPrice").hide();
                        //var ctemp = productgrid.getColumns();
                        var datatemp = productgrid.getData();
                        var cs = [];
                        cs.push({
                            id: "ProdID", name: "", field: "ProdID", minWidth: 60, formatter: function (r, c, value, def, datactx) {
                                return getProductName(value);
                            }
                        });

                        cs.push({ id: "NDPrice", name: "NDPrice", field: "NDPrice", minWidth: 60, cssClass: 'NDPriceCss' });
                        var columnSelection = [];
                        $.each(datatemp, function (key, value) {
                            if (value.ParentText != undefined && value.ParentText != 'null') {
                                cs.push({ parentable: 1, dc: value.DC, id: value.CuctID, name: '(DC ' + value.DC + ') ' + getCustomerName(value.CuctID) + "(" + value.ParentText + ")", field: value.CuctID, minWidth: 60, width: 150, formatter: Slick.Formatters.DisableSupport, editor: Slick.Editors.Price });
                            }
                            else {
                                cs.push({ parentable: 1, dc: value.DC, id: value.CuctID, name: '(DC ' + value.DC + ') ' + getCustomerName(value.CuctID), field: value.CuctID, minWidth: 60, width: 150, formatter: Slick.Formatters.DisableSupport, editor: Slick.Editors.Price });
                            }
                            columnSelection.push(value.CuctID);
                        });

                        var datas = [];
                        var r = 0;
                        $.each(datatemp, function (name, value) {
                            var i = 0;
                            $.each(products, function (pi, pv) {
                                var prop = pv.mprodh_grpID;

                                //});
                                //for (var prop in value) {
                                if (isNumber(prop)) {
                                    var dataItem = {};
                                    if (r > 0) {
                                        dataItem = datas[i];
                                    }

                                    if (value[prop] === true) {
                                        if (r <= 0) {
                                            dataItem.ProdID = prop;
                                            dataItem.NDPrice = pv.discountPrice; //getNDPrice(prop,'discountPrice');
                                            dataItem.NDPriceApprove1 = pv.NDApproverLevel1; //getNDPrice(prop,'NDApproverLevel1');
                                            dataItem.NDPriceApprove2 = pv.NDApproverLevel2; //getNDPrice(prop,'NDApproverLevel2');
                                            dataItem.NDPriceApprove3 = pv.NDApproverLevel3; //getNDPrice(prop,'NDApproverLevel3');
                                        }
                                        dataItem.CuctID = value.CuctID;
                                        dataItem[value.CuctID] = '';
                                        //this[prop] = '';
                                    }
                                    else if (value[prop] === false) {
                                        if (r <= 0) {
                                            dataItem.ProdID = prop;
                                            dataItem.NDPrice = pv.discountPrice; //getNDPrice(prop,'discountPrice');
                                            dataItem.NDPriceApprove1 = pv.NDApproverLevel1; //getNDPrice(prop,'NDApproverLevel1');
                                            dataItem.NDPriceApprove2 = pv.NDApproverLevel2; //getNDPrice(prop,'NDApproverLevel2');
                                            dataItem.NDPriceApprove3 = pv.NDApproverLevel3; //getNDPrice(prop,'NDApproverLevel3');
                                        }
                                        dataItem[value.CuctID] = 'N/A';
                                        //this[prop] = 'N/A';
                                    }

                                    if (r > 0) {

                                        datas[i] = dataItem;
                                    }
                                    else {
                                        datas.push(dataItem);
                                    }
                                }
                                if (isNumber(prop)) {
                                    i = i + 1;
                                }
                                //}
                            });
                            r = r + 1;


                        });

                        RefreshGridDiscount(datas, cs, optionsProductGrid, columnSelection);

                        $('#txtValidOn').attr('readonly', 'readonly');
                        $('#txtValidTo').attr('readonly', 'readonly');
                        $("#txtValidOn").datepicker({ dateFormat: 'yy-mm-dd', minDate: new Date(), showOn: "button", buttonImage: "/images/calendar.gif", buttonImageOnly: true });
                        $("#txtValidTo").datepicker({ dateFormat: 'yy-mm-dd', showOn: "button", buttonImage: "/images/calendar.gif", buttonImageOnly: true });
                        $("#txtValidOn").change(function () {
                            var test = $(this).datepicker('getDate');
                            //var testm = new Date(test.getTime());
                            // var testm.setDate(testm.getDate() + 1);
                            //$("#endDate").datepicker("option", "minDate", testm);
                            $("#txtValidTo").datepicker("option", "minDate", test);
                        });

                    }

                default:
            }
        }
        function InsertHeaderDescription(columnID) {
            if (columnID.toolTip != undefined && columnID.toolTip != null && columnID.toolTip != 'null') {
                $("#txtParentHeader").val(columnID.toolTip);
            }
            else {
                $("#txtParentHeader").val("");
            }
            $("#dialog-parentAdd").dialog({
                autoOpen: false,
                resizable: false,
                height: 180,
                dialogClass: "Dialog",
                modal: true,
                buttons: {
                    Save: function () {
                        var c = discountgrid.getColumns();
                        jQuery.each(c, function (i, d) {
                            if (d.id == columnID.id) {
                                if (d.toolTip != null) {
                                    var str = d.name;
                                    var n = str.lastIndexOf('(');
                                    var result = str.substring(0, n);
                                    d.name = result + "(" + jQuery('#txtParentHeader').val() + ")";
                                }
                                else {
                                    d.name = d.name + "(" + jQuery('#txtParentHeader').val() + ")";
                                }
                                d.toolTip = jQuery('#txtParentHeader').val();
                                discountgrid.updateColumnHeader(d.id, d.name, d.toolTip);
                            }
                        });

                        $(this).dialog("close");
                    }//,
                    //                        Ok: function() {
                    //                            $( this ).dialog( "close" );
                    //
                    //                        }
                }
            });
            $('#dialog-parentAdd').dialog("open");
            var top = ($(window).height() - 250) / 2;
            var left = ($(window).width() - 350) / 2;
            $(".Dialog").css('left', left);
            $(".Dialog").css('top', top);
        }
        function chageAllPrice(isAdd, numberChange) {
            approveLevel = 0;
            var datas = discountgrid.getData();
            var cs = discountgrid.getColumns();
            if (isAdd) {

                $.each(cs, function (name, value) {
                    var dc = value.dc;

                    var custId = value.id;
                    if (dc != undefined) {
                        for (var v in datas) {

                            if (datas[v][custId] != 'N/A') {
                                var oldvalue = datas[v][custId];
                                if (oldvalue === '' || oldvalue === undefined) {
                                    datas[v][custId] = (datas[v].NDPrice - numberChange);
                                }
                                else {
                                    datas[v][custId] = (parseFloat(parseFloat(oldvalue) - numberChange)).toFixed(2);
                                }

                            }
                        };
                    }
                });

                RefreshGridDiscount(datas, cs, optionsProductGrid);
            }
            else {
                $.each(cs, function (name, value) {
                    var dc = value.dc;

                    var custId = value.id;
                    if (dc != undefined) {
                        for (var v in datas) {

                            if (datas[v][custId] != 'N/A') {
                                var oldvalue = datas[v][custId];
                                if (oldvalue === '' || oldvalue === undefined) {
                                    oldvalue = 0;
                                }
                                datas[v][custId] = parseInt(parseInt(oldvalue) - numberChange);
                            }
                        };
                    }
                });

                RefreshGridDiscount(datas, cs, optionsProductGrid);
            }

        }
        function saveDocument(docType, status, creditTerm) {
            //if (validateBlankCell() == true) {
            var doctype = docType;
            var validon = $.datepicker.formatDate('yy-mm-dd', $('#txtValidOn').datepicker('getDate'));

            var validto = $.datepicker.formatDate('yy-mm-dd', $('#txtValidTo').datepicker('getDate'));
            var remark = $('#remark').val();
            var remark2 = $('#remark2').val();
            var completedata = [];

            var datas = discountgrid.getData();
            var columns = discountgrid.getColumns();
            $.each(columns, function (name, value) {
                var dc = value.dc;
                var parent = value.toolTip;
                var custId = value.id;
                if (dc != undefined) {
                    $(datas).each(function () {
                        var item = {};
                        item.DCID = dc;
                        item.RefID = custId;
                        item.Parent = parent;
                        if (this.ProdID === undefined) {
                            item.ProductDesc = this.ProductDesc;
                        }
                        else {
                            item.ProductID = this.ProdID;
                        }
                        item.NDPrice = this.NDPrice;
                        item.discountPrice = this[custId];
                        if (item.discountPrice != 'N/A') {
                            completedata.push(item);
                        }


                    });
                }
            });

            var data = {
                Doctype: doctype,
                Status: status,
                ValidOn: validon,
                ValidTo: validto,
                Remark: remark,
                Remark2: remark2,
                ApproveLevel: approveLevel,
                CreditTerm: creditTerm,
                data: completedata
            };
            if (draftDocID && isneednewID != true) {
                data['docID'] = draftDocID;
            }
            helper.InserDocument(data, function (result) {
                MsgBox('Save Document success');
                window.location.reload(true);
            });
            //}
        }

        function validateBlankCell() {
            var datas = discountgrid.getData();
            var cs = discountgrid.getColumns();
            var result = true;
            //return result;
            $.each(cs, function (name, value) {
                var dc = value.dc;
                var custId = value.id;
                if (dc != undefined) {
                    for (var v in datas) {

                        if (datas[v][custId] != 'N/A') {
                            var oldvalue = datas[v][custId];
                            if (oldvalue === '' || oldvalue === undefined) {
                                //$(".slick-cell l2 r2").trigger('click');
                                MsgBox("Please correct data on customer " + getCustomerName(custId) + " and product " + datas[v].ProductDesc);
                                result = result && false;
                                return false;
                            }
                        }
                    };
                }
            });
            if ($('#remark').val() == '' || $('#remark').val() == undefined) {
                MsgBox("กรุณาระบุข้อมูลในช่อง Remark");
                $('#dialogMessageID').text("กรุณาระบุข้อมูลในช่อง Remark");
                $("#dialog-message").dialog("open");
                var top = ($(window).height() - 250) / 2;
                var left = ($(window).width() - 350) / 2;
                $(".Dialog").css('left', left);
                $(".Dialog").css('top', top);
                return false;
            }
            return result;
        }
        function getCustomerName(custID) {
            var result = custID;
            $.map(custsAllDC, function (obj) {
                if (obj.mcustno === custID) {
                    result = obj.mcustname1;
                }
            });
            return result;
        }

        function getProductName(prodID) {
            var result = prodID;
            $.map(products, function (obj) {
                if (obj.mprodh_grpID === parseInt(prodID)) {
                    result = obj.mprodh_grpname;
                }
            });
            return result;
        }
        function getNDPrice(prodID, attrLooking) {
            var result = prodID;
            $.each(products, function (key, value) {
                if (prodID === value['mprodh_grpID'].toString()) {

                    result = value[attrLooking];
                }
            });

            return result;
        }
        function loadFrm(url) {

            $.get(url, function (content) {

                $('#mainFrame').html(content);

            });
        }


        var ProductListBoxItem = JSListBox.Item.extend({

            text: "",
            kvalue: "",
            init: function (text, value) {
                this.text = text;
                this.kvalue = value;
            },

            render: function () {
                return '<a value=' + this.kvalue + ' href="#">' + this.text + '</a>';
            },

            onClick: function () {
                customerID = this.kvalue;
                customerName = this.text;
                //alert(item.value);
            },

            onDblClick: function () {
                var item = new JSListBox.Item();
                item.kvalue = this.text + " item double clicked.";
                item.enabled = false;
                //alert(item.value);
            }

        });

        var helper = new Helper();
        function isExistAddStep2(cusID) {
            for (var i = 0; i < productGridData.length; i++) {
                if (productGridData[i].CuctID === cusID) {
                    return true;
                }
            }
            return false;

        }

        function CustomerProductiMappingInit(parameters) {
            $("#Options").dropdownchecklist();
            //CustInit();
            ProductInit();

            //Init button
            $("#btnProdSave")
			.button({

			    icons: {
			        primary: "ui-icon-plus"
			    },
			})
			.click(function () {
			    if (customerID === '') {
			        var top = ($(window).height() - 250) / 2;
			        var left = ($(window).width() - 350) / 2;
			        var message = 'Please select customer.';
			        if ($.cookie('apptype') === '02') {
			            message = 'Please select price group.';
			        }
			        $('#dialogMessageID').text(message);
			        $("#dialog-message").dialog("open");
			        $(".Dialog").css('left', left);
			        $(".Dialog").css('top', top);
			    }
			    else {
			        if (isExistAddStep2(customerID) == false) {
			            if (!isMaximumCustomer()) {
			                RefreshGridCustomerProduct();
			                $("#chbAllProduct").attr('checked', false);
			                $('#productChecklist li input:checkbox').each(function () {
			                    $(this).attr('checked', false);

			                });
			            }
			            else {
			                var top = ($(window).height() - 250) / 2;
			                var left = ($(window).width() - 350) / 2;
			                var message = 'Allow only 10 customer per document.';
			                if ($.cookie('apptype') === '02') {
			                    message = 'Allow only 10 customer per document.';
			                }
			                $('#dialogMessageID').text(message);
			                $("#dialog-message").dialog("open");
			                $(".Dialog").css('left', left);
			                $(".Dialog").css('top', top);
			            }
			        }
			        else {
			            var top = ($(window).height() - 250) / 2;
			            var left = ($(window).width() - 350) / 2;

			            var message = 'The customer already added to the list.';
			            if ($.cookie('apptype') === '02') {
			                message = 'The price group already added to the list.';
			            }
			            $('#dialogMessageID').text(message);
			            $("#dialog-message").dialog("open");
			            $(".Dialog").css('left', left);
			            $(".Dialog").css('top', top);
			        }
			    }

			});

            $("#btnProdFinish")
             .button({

                 icons: {
                     primary: "ui-icon-note"
                 },
             })
             .click(function () {
                 var rowBlank = ValidateCheckedProduct(productgrid.getData());
                 if (productgrid === undefined || rowBlank != '') {
                     var top = ($(window).height() - 250) / 2;
                     var left = ($(window).width() - 350) / 2;
                     var message = 'Please select product on row ' + rowBlank;
                     $('#dialogMessageID').text(message);
                     $("#dialog-message").dialog("open");
                     $(".Dialog").css('left', left);
                     $(".Dialog").css('top', top);

                 } else {

                     $('#mainFrame').html($('#gridproductDetail').html());
                     showLayout('3');
                 }
                 //RefreshGridDiscount();
                 //buttonInit();
                 //			    var doctype = '01';
                 //			    var data = { Doctype: doctype, data: datas };
                 //			    helper.InserDocument(data, function(result) {
                 //			        alert(result);
                 //			    });

             });

            $("#ButtonSearch").button({

                icons: {
                    primary: "ui-icon-search"
                }
            })
			.click(function () {

			    CustInit();
			});

            $('#TextDCtex').keydown(function (e) {
                if (e.keyCode == 13) {

                    CustInit();
                }

            });

        }

        function isMaximumCustomer() {
            if (productgrid != undefined && productgrid.getData().length >= 10) {
                return true;
            }
            return false;
        }

        function ValidateCheckedProduct(data) {
            var selectedBlank = '';
            var isCheck = false;
            $.each(data, function (key, value) {
                for (var prop in value) {
                    if (value[prop] === true) {
                        isCheck = true;
                        break;
                    }
                }
                if (isCheck == false) {
                    if (selectedBlank != '') {
                        selectedBlank += ',';
                    }
                    selectedBlank += (key + 1);
                }

            });
            return selectedBlank;
        }

        var custsAllDC = [];
        var custs = [];
        var custList = [];
        function CustInit() {
            custs = [];
            custList = [];
            helper.GetCustomerBySaleAllDc($.cookie("apptype"), function (data) {
                custsAllDC = data.AllCustomer;
            });
            helper.GetCustomerBySaleGrp($('#TextDCtex').val(), $.cookie("apptype"), function (data) {
                custs = data.AllCustomer;
                window.listBoxAllItems = new JSListBox({ 'containerSelector': 'ListBoxCustomerItems' });
                $.each(custs, function (key, value) {
                    if ($.cookie("apptype") === '02') {
                        custList.push(new ProductListBoxItem(value["mcustno"], value["mcustno"]));
                    }
                    else {
                        custList.push(new ProductListBoxItem(value["mcustname1"], value["mcustno"]));
                    }
                });
                window.listBoxAllItems.addItems(custList);
            });

            //           for (var i = 0; i < 5; i++) {
            //               var cust = (custs[i] = { });
            //               cust["custtext"] = "ลูกค้า " + i;
            //               cust["custvalue"] = 'c' + i;
            //           }


        }

        function buttonInit(parameters) {


            $('#menuAddStep1').button({

                icons: {
                    primary: "ui-icon-plus"
                }
            })
             .click(function () {

                 showLayout('2');
             });
            $("#btnBackToSelectDoctypeFromDocList").button({

                icons: {
                    primary: "ui-icon-circle-arrow-w"
                }
            })
                 .click(function () {
                     $.cookie("apptype", '', { path: '/' });
                     window.location.reload(true);
                 });
            $("#btnExit").button({

                icons: {
                    primary: "ui-icon-circle-arrow-n"
                }
            })
			    .click(function () {
			        exitToFirstPage();
			    });


            //             $('#menuEditStep1').button({
            //
            //                icons: {
            //                    primary: "ui-icon-pencil"
            //                }
            //            })
            //			.click(function () {
            //
            //			});
            //
            //             $('#menuDeleteStep1').button({
            //
            //                icons: {
            //                    primary: "ui-icon-minus"
            //                }
            //            })
            //			.click(function () {
            //
            //			});


        }
        function exitToFirstPage() {
            $.cookie("apptype", '', { path: '/' });
            $.cookie("saleID", null, { path: '/' });
            window.location.reload(true);
        }

        function searchDocument(key) {
            if (key == 13) {
                event.cancelBubble = true;
                return false;
            }
            var searchText = $("#txtQuickFilterDoc").val();
            var filterDocs = jQuery.grep(allDocs, function (element, index) {
                return element.DocID.toLowerCase().indexOf(searchText.toLowerCase()) != -1 || element.UserName.toLowerCase().indexOf(searchText.toLowerCase()) != -1;
            });

            var constGrid = 'grid';
            var constAllstatus = 'all';
            documentgrids[constAllstatus].setData(filterDocs);
            documentgrids[constAllstatus].render();
            $.each(allTab, function (key, value) {
                var datas;
                datas = jQuery.grep(filterDocs, function (n, i) {
                    return (n.Status === value.StatusID);
                });
                documentgrids[value.StatusID].setData(datas);
                documentgrids[value.StatusID].render();
                //GridDocumentInit('#' + constGrid+ value.StatusID ,filterDocs,value.StatusID);
            });

        }

        function searchSale(key) {
            if (key == 13) {
                event.cancelBubble = true;
                return false;
            }
            var searchText = $("#txtSearchSale").val();
            var filterSales = jQuery.grep(sales, function (element, index) {
                return element.UserName.toLowerCase().indexOf(searchText.toLowerCase()) != -1 || element.FirstName.toLowerCase().indexOf(searchText.toLowerCase()) != -1 || element.Lastname.toLowerCase().indexOf(searchText.toLowerCase()) != -1 || element.msalegrp.toLowerCase().indexOf(searchText.toLowerCase()) != -1;
            });
            var salesList = [];
            $.each(filterSales, function (key, value) {
                salesList.push(new SaleListBoxItem(value["FirstName"] + " " + value["Lastname"], value["UserName"]));
            });
            window.listBoxAllItems.clear();
            window.listBoxAllItems.addItems(salesList);

        }

        var products = [];
        function ProductInit() {
            products = [];
            var htmlcomp = '';
            var htmltemplate = '<li class="ui-menu-item" ><div class="ui-dropdownchecklist-item ui-state-default ui-corner-all" style="padding: 0.2em 0.4em;"><input ndprice="{2}" type="checkbox" tabindex="0" class="active" id="ddcl-Options-i0" index="0"value="{0}"><label for="ddcl-Options-i0" class="ui-dropdownchecklist-text"style="cursor: default; font-size:12px; padding: 0.2em 0.4em;">{1}</label></div></li>';
            helper.GetProductToSale(function (data) {
                products = data.AllProduct;
                $.each(products, function (key, value) {
                    htmlcomp += htmltemplate.format(value.mprodh_grpID, value.mprodh_grpname, value.discountPrice);
                });

                $('#productChecklist ul').html(htmlcomp);

            });

            $('#chbAllProduct').click(function () {
                if ($(this).is(':checked')) {
                    $('#productChecklist li input:checkbox').each(function (value) {
                        $(this).attr('checked', true);
                    });
                }
                else {
                    $('#productChecklist li input:checkbox').each(function (value) {
                        $(this).attr('checked', false);
                    });
                }

            });
        }

        function getProductSelect(iscolumn) {
            var produxtselected = [];
            if (iscolumn) {
                $('#productChecklist li input:checkbox').each(function (value) {
                    columns.push({ id: $(this).next().text(), name: $(this).next().text(), field: $(this).val(), minWidth: 60, formatter: Slick.Formatters.Checkmark, editor: Slick.Editors.Checkbox });
                });
                return produxtselected;
            }
            else {
                var product = {};
                product[columns[0].field] = 'Delete';
                product[columns[1].field] = 'ID';
                product[columns[2].field] = $('#TextDCtex').val();
                product[columns[3].field] = customerID;

                $('#productChecklist li input:checkbox').each(function (value) {
                    var cons = 4;
                    product[columns[value + cons].field] = $(this).is(':checked');

                });
                return product;
            }

        }
        var productgrid;
        var optionsProductGrid = {
            editable: true,
            enableRowReordering: true,
            enableCellNavigation: true,
            asyncEditorLoading: false,
            autoEdit: true
        };

        var productGridData = [];
        var productGridDiscountData = [];
        var customerID = '';
        var customerName = '';
        var columns = [];
        var discountcolumns = [];
        function createColumnGrid() {
            columns = [];
            columns.push({
                id: 'Delete', name: 'Delete', field: 'Delete', formatter: function (r, c, id, def, datactx) {
                    return '<a href="#" onclick="RemoveClick(' + r + ')">X</a>';
                }
            });
            columns.push({
                id: 'ID', name: 'ID', formatter: function (row) {
                    return row + 1;
                }
            });
            columns.push({ id: 'DC', name: 'DC', field: 'DC' });
            columns.push({
                id: 'CustID', name: 'CustID', field: 'CuctID', formatter: function (r, c, value, def, datactx) {

                    return getCustomerName(value);
                }
            });
            getProductSelect(true);


            return columns;
        }

        function createColumnDiscountGrid(columns, isDeleteCommandColumn) {
            discountcolumns = columns;
            if (isDeleteCommandColumn) {
                discountcolumns.splice(0, 3);
            }
            $(discountcolumns).each(function (index) {
                if (index != 0) {
                    this.formatter = Slick.Formatters.DisableSupport;
                    this.editor = Slick.Editors.Integer;
                }
            });
            return discountcolumns;
        }

        function createDataDiscountGrid() {
            productGridDiscountData = productGridData;
            $(productGridDiscountData).each(function () {
                var k = this;

                for (var prop in k) {
                    if (k[prop] === true) {
                        this[prop] = '';
                    }
                    else if (k[prop] === false) {
                        this[prop] = 'N/A';
                    }

                }

                //               $.each(k, function(name, value) {
                //                   if(value === true ) {
                //                       //value = '';
                //                       k[name] = '';
                //                   }
                //                   else if(value === false) {
                //                       k[name] = -1;
                //                   }
                //               });

            });

        }
        function RemoveClick(gridRow) {
            //alert((databaseId));
            //alert(gridRow);
            productGridData.splice(gridRow, 1);
            productgrid.setData(productGridData);
            productgrid.render();
        }
        function ProdData(event, data) {
            switch (event) {
                case 'insert':
                    productGridData.push(getProductSelect());
                default:
            }
        }
        function findColumnIndex(cs, columnName) {
            for (var i = 0; i < cs.length; i++) {
                if (cs[i].field === columnName) {
                    return i;
                }
            }
        }
        var productgrid;
        function RefreshGridCustomerProduct(parameters) {
            var columns = createColumnGrid();
            ProdData('insert', getProductSelect());
            var datas = productGridData;
            productgrid = new Slick.Grid("#SaleCustomerGrid", datas, columns, optionsProductGrid);
            productgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));
            productgrid.onCellChange.subscribe(function (e, args) {
                //updateUser(args.item);
            });
        }

        var discountgrid;
        function RefreshGridDiscount(datas, cs, options, columnSection) {
            if (columnSection != undefined || columnSection != null) {

                datas = $.map(datas, function (item, index) {
                    var ii = 0;
                    $.each(columnSection, function (i2, value) {
                        if (item[value] === 'N/A') {
                            ii++;
                        }
                    });
                    if (ii >= columnSection.length) {
                        return null; // Removes items those unselected on all customer;
                    }
                    else {
                        return item;
                    }
                });

            }
            if (discountgrid != undefined) {
                discountgrid = new Slick.Grid("#SaleCustomerDetailGrid", datas, cs, options);
                discountgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));

                discountgrid.onBeforeEditCell.subscribe(function (e, args) {
                    var value = datas[args.row][discountgrid.getColumns()[args.cell].field];
                    if (value === 'N/A') {
                        return false;
                    } else {
                        return true;
                    }

                });
                discountgrid.onCellChange.subscribe(function (e, args) {
                    $('#realApprove').text(getRealApproval());
                });
                discountgrid.onHeaderClick.subscribe(function (e, args) {
                    var columnID = args.column;
                    if (args.column.parentable == 1) {

                        InsertHeaderDescription(columnID);
                    }
                });
            } else {
                discountgrid = new Slick.Grid("#SaleCustomerDetailGrid", datas, cs, options);
                discountgrid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true }));

                discountgrid.onBeforeEditCell.subscribe(function (e, args) {
                    var value = datas[args.row][discountgrid.getColumns()[args.cell].field];
                    if (value === 'N/A') {
                        return false;
                    } else {
                        return true;
                    }
                });
                discountgrid.onHeaderClick.subscribe(function (e, args) {
                    var columnID = args.column;
                    if (args.column.parentable == 1) {

                        InsertHeaderDescription(columnID);
                    }
                });
            }
            $('#realApprove').text(getRealApproval(datas, cs));

            discountgrid.onCellChange.subscribe(function (e, args) {
                $('#realApprove').text(getRealApproval());
            });
        }

        var approveLevel = 0;
        function getRealApproval(datas, cs) {
            if (datas === undefined) {
                datas = discountgrid.getData();
                cs = discountgrid.getColumns();
            }
            approveLevel = 0;
            $.each(cs, function (name, value) {
                var custId = value.id;
                if (value.dc != undefined) {
                    for (var v in datas) {
                        if (datas[v][custId] != 'N/A') {
                            var currentInputValue = datas[v].NDPrice - datas[v][custId];
                            if (currentInputValue <= datas[v].NDPriceApprove1) {
                                $('#approveLevelDetails').show();
                            }
                            else if (currentInputValue > datas[v].NDPriceApprove1 && currentInputValue <= datas[v].NDPriceApprove2) {
                                if (approveLevel < 1) {
                                    approveLevel = 1;
                                    $('#approveLevelDetails').show();
                                }
                            }
                            else if (currentInputValue > datas[v].NDPriceApprove2) {
                                if (approveLevel < 2) {
                                    approveLevel = 2;
                                    $('#approveLevelDetails').show();
                                }
                            }
                            //                           else if (currentInputValue > datas[v].NDPriceApprove2 && currentInputValue <= datas[v].NDPriceApprove3) {
                            //                               if (approveLevel < 2) {
                            //                                   approveLevel = 2;
                            //                                   $('#approveLevelDetails').show();
                            //                               }
                            //                           }
                            //                           else if (currentInputValue > datas[v].NDPriceApprove3) {
                            //                               if (approveLevel < 3) {
                            //                                   approveLevel = 3;
                            //                                   $('#approveLevelDetails').show();
                            //                               }
                            //                           }
                        }
                    };
                }
            });
            var approvalDisaplay = "";
            $.each(approverAll.AllApprover, function (i, v) {
                if (v.approveLevel == approveLevel) {
                    approvalDisaplay += "   อำนาจอนุมัติ: " + v.approveDisplay;
                }
            });
            return approvalDisaplay;
        }
        var sales = [];
        var salesList = [];
        function SaleInit() {
            sales = [];
            salesList = [];
            helper.GetSaleClientBySaleCo(function (data) {
                sales = data.AllSale;
                window.listBoxAllItems = new JSListBox({ 'containerSelector': 'ListBoxSaleItems' });
                $.each(sales, function (key, value) {
                    salesList.push(new SaleListBoxItem(value["FirstName"] + " " + value["Lastname"], value["UserName"]));
                });
                window.listBoxAllItems.addItems(salesList);
            });
        }
        var saleID;
        var saleName;
        var SaleListBoxItem = JSListBox.Item.extend({

            text: "",
            kvalue: "",
            init: function (text, value) {
                this.text = text;
                this.kvalue = value;
            },

            render: function () {
                return '<a value=' + this.kvalue + ' href="#">' + this.text + '</a>';
            },

            onClick: function () {
                saleID = this.kvalue;
                saleName = this.text;
                //alert(item.value);
            },

            onDblClick: function () {
                var item = new JSListBox.Item();
                item.kvalue = this.text + " item double clicked.";
                item.enabled = false;
                //alert(item.value);
            }

        });

        function openDocumentCompleted(docID, docType) {
            showLayout("3", docID, docType, true, true);
        }
        var gridNDPrice;
        function getColumn(parameters) {
            var columnNDPriceGrid = [];
            columnNDPriceGrid.push({
                id: 'mprodh_grpname', name: 'Product', field: 'mprodh_grpname'
            });
            columnNDPriceGrid.push({
                id: 'NDPrice', name: 'NDPrice', field: 'discountPrice'
            });
            columnNDPriceGrid.push({
                id: 'NDApproverLevel1', name: 'NDApproverLevel1', field: 'NDApproverLevel1', width: 100
            });
            columnNDPriceGrid.push({
                id: 'NDApproverLevel2', name: 'NDApproverLevel2', field: 'NDApproverLevel2', width: 100
            });
            columnNDPriceGrid.push({
                id: 'NDApproverLevel3', name: 'NDApproverLevel3', field: 'NDApproverLevel3', width: 100
            });
            return columnNDPriceGrid;
        }
        var optionsNDprice = {
            editable: true,
            enableRowReordering: true,
            enableCellNavigation: true,
            asyncEditorLoading: false,
            autoEdit: true
        };

        function showNdPriceDetail(roundID) {

            helper.GetNDPriceByID(roundID, function (ndPricedata) {
                var gridNDPrice = new Slick.Grid("#NDPriceGrid", ndPricedata.RMember, getColumn(), optionsNDprice);
            });

            var top = ($(window).height() - 250) / 2;
            var left = ($(window).width() - 350) / 2;
            $("#DivNdpriceDetails").dialog("open");
            $(".Dialog").css('left', left);
            $(".Dialog").css('top', top);
        }
        function sortJsonArrayByProp(objArray, prop) {
            if (arguments.length < 2) {
                throw new Error("sortJsonArrayByProp requires 2 arguments");
            }
            if (objArray.constructor === Array) {
                var propPath = (prop.constructor === Array) ? prop : prop.split(".");
                objArray.sort(function (a, b) {

                    if (a[propPath] && b[propPath]) {
                        a = a[propPath];
                        b = b[propPath];
                    }

                    // convert numeric strings to integers
                    a = a.match(/^\d+$/) ? +a : a;
                    b = b.match(/^\d+$/) ? +b : b;
                    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
                });
            }
        }
    </script>
</head>
<body>
    <div class="ui-layout-north ui-widget-content" style="display: none;">
        <div id="main_header">
            <div class="logo" style="float: left; margin-top: 10px;">
                <img src="/images/logoNawa.png" alt="Nawaplastic Co.,Ltd." />
            </div>
            <div style="float: left; margin-top: 10px; margin-left: 100px;">
                <span style="font-family: verdana; font-size: 16px; font-weight: bold;" class="ui-state-highlight"
                      id="curTime"></span>
            </div>
            <div style="float: right; margin-right: 160px;">
                <div>
                    <div style="width: 70px; float: left">
                        User as:
                    </div>
                    <span class="userInfo" id="userNameShow">UserName</span><br />
                    <div style="width: 70px; float: left">
                        Logged in as:
                    </div>
                    <span class="userInfo" id="SpanUserIP">IP</span>
                    <br />
                    <div style="width: 70px; float: left">
                        Role as :
                    </div>
                    <span class="userInfo" id="SpanRoleShow">Role</span>
                </div>
            </div>
        </div>
        <div id="toolbarHolder">
            <div class="ui-state-default ui-corner-all ui-helper-clearfix">
                <ul id="main-menu" class="jd_menu dropdown ui-widget-header" onmouseover="myLayout.allowOverflow('north')"
                    onmouseout="myLayout.resetOverflow(this)">
                    <li>
                        <a href="#">Application &raquo;</a>
                        <ul class="ui-state-default">
                            <li><a href="/Page/SaleCoMain.htm">SaleCo Management</a></li>
                        </ul>
                    </li>
                    <li>
                        <a href="#">Reports&raquo;</a>
                        <ul class="ui-state-default">
                            <li>
                                <a target="blank" href="/Page/documentSelectToReport.htm" onclick="window.open(this.href,'window','width=700,height=720,resizable,scrollbars,toolbar,menubar') ;return false;">
                                    Report
                                </a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div id="MessageBar" class="ui-layout-south ui-widget-content ui-state-error" style="display: none;">
        Message Bar
    </div>
    <div id="mainFrame" class="ui-layout-center" width="100%" height="600" frameborder="0"
         scrolling="auto">
    </div>
    <div id="SelectSaleDiv" style="display: none">
        <div class="DCTextClass ">
            Select Sale:
            <input id="txtSearchSale" type="text" class="ui-widget ui-widget-content ui-corner-all ui-menu-item" />
            <button id="btnSearchSale">
                Search
            </button>
        </div>
        <div id="ListBoxSaleItems" style="height: 60%; width: 350px;">
        </div>
        <div class="DCTextClass ">
            <button id="btnSelectSale">
                Select
            </button>
        </div>
    </div>
    <div id="docTypeSelect" style="display: none">
        <div style="height: 347px; width: 340px;" class="panel" id="Panel1">
            <div class="boxhead">
                <h2 id="Panel1Label">
                    please select : application.
                </h2>
            </div>
            <div class="boxbody">
                <div style="width: auto; height: 201px;" class="content" id="Panel1_content">
                    <div style="text-align: left; padding: 10px;" id="Panel1_innerContent" class="innerContent">
                        <div style="padding: 10px 0px 0px 0px;">
                            <p style="margin: 0px; padding: 5px 0px 20px 0px; color: #999">
                                please select : application:
                            </p>
                            <table cellspacing="0" cellpadding="0" border="0" id="loginTable">
                                <tbody>
                                    <tr>
                                        <td align="right">
                                            <label id="username" for="lname">
                                                Customer
                                            </label>
                                        </td>
                                        <td>
                                            <input id="RadioCustomer" type="radio" name="group1" checked="checked" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="height: 12px;" colspan="2"></td>
                                    </tr>
                                    <tr>
                                        <td align="right">
                                            <label id="password" for="passw">
                                                Price Group
                                            </label>
                                        </td>
                                        <td>
                                            <input id="RadioPriceGroup" type="radio" name="group1" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="height: 12px;" colspan="2"></td>
                                    </tr>
                                    <tr>
                                        <td style="height: 12px;" colspan="2">
                                            <br />
                                            <!--<input id="btnNext" name="Next" type="button" value="Next" onclick="javascript:SelectApplication();" />-->
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <div>
                                <button id="btnBackToSelectSale">
                                    Back
                                </button>
                                <button id="btnNext">
                                    Next
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="boxfooter">
                <div class="statusBar">
                    <h2></h2>
                </div>
            </div>
        </div>
    </div>
    <div id="DocumentManageStep" style="display: none">
        <div style="padding-top: 10px; padding-bottom: 30px; padding-left: 10px; padding-right: 10px;">
            <span id="toolbar" class=" ui-corner-all" style="float: left">
                <button id="btnBackToSelectDoctypeFromDocList">
                    Back
                </button>
                <button class="ui-state-highlight" id="btnExit">
                    Exit
                </button>
                <button id="menuAddStep1">
                    ADD
                </button>
                <!-- <button id="menuEditStep1">
                         Edit</button>
                    <button id="menuDeleteStep1">
                        Delete</button>-->
            </span><span style="float: right">
                Quick Search&nbsp;<input id="txtQuickFilterDoc"
                                         type="text" maxlength="50" />
                <button id="bthQuickSearchDoc">
                    Search
                </button>
            </span>
        </div>
        <div id="tabs">
        </div>
    </div>
    <div id="customerProductStep" style="display: none">
        <div class="inner-center">
            <div style="height: 20px;">
            </div>
            <div id="productChecklist" class="ui-widget ui-widget-content ui-corner-all" style="width: 50%;
                height: 80%; margin-left: 50px; margin-bottom: 10px; overflow: auto;">
                <div class="ui-widget-header" style="width: 99%;">
                    <input style="margin-left: 4px; margin-right: 7px;" type="checkbox" id="chbAllProduct" />
                    All Product:
                </div>
                <ul></ul>
            </div>
            <div style="margin-left: 50px;">
                <button id="btnProdSave">
                    ADD
                </button>
                <!-- <button id="btnProdNew">
                    Save</button>-->
                <button id="btnProdFinish">
                    Finish
                </button>
            </div>
        </div>
        <div class="inner-west">
            <div class="DCTextClass ">
                DC :
                <input id="TextDCtex" type="text" class="ui-widget ui-widget-content ui-corner-all ui-menu-item"
                       style="width: 150px" />
                <button id="ButtonSearch">
                    Search
                </button>
            </div>
            <div id="ListBoxCustomerItems" style="height: 80%;">
            </div>
        </div>
        <div class="ui-layout-south">
            <div id="SaleCustomerGrid" style="width: 90%; height: 90%; overflow: scroll">
            </div>
        </div>
    </div>
    <div id="gridproductDetailStep" style="display: none;">
        <div style="padding-top: 10px; padding-bottom: 30px; padding-left: 10px; padding-right: 10px;">
            <span id="Span1" class=" ui-corner-all" style="float: left">
                Valid On
                <input id="txtValidOn" type="text" />
                valid To
                <input id="txtValidTo" type="text" />
            </span>
            <div class="ui-state-highlight" style="float: left; margin-left: 10px; font-size: large">
                <span style="font-size: large" id="SpanDocIDCaption">Document ID: </span><span style="font-size: large"
                                                                                               id="txtDocID"></span>
            </div>
            <span style="float: right;" id="SpanAddPrice">
                <input id="txtaddPrice" type="text" />
                <button id="btnAddPrice" style="margin-left: 5px;" class="ui-state-highlight">
                    Submit
                </button>
            </span>
        </div>
        <div>
            <div style="color: red; font-size: large; margin-bottom: 5px;">
                เอกสารฉบับนี้จะมีผล ณ. วันที่ upload ราคาเข้าระบบ SAP
            </div>
            <div style="float: left; margin-bottom: 5px;">
                <button id="btnBackToDocList">
                    Back
                </button>
                <button class="ui-state-highlight" id="btnExit2">
                    Exit
                </button>
            </div>
            <div id="approveLevelDetails" style="float: left; display: none">
                <span style="padding-left: 10px;" class="ui-widget-content">
                    ต้องการ <span id="approvalDisplay">
                    </span>อนุมัติ
                </span> <span style="padding-left: 10px;" class="highlightPriceApporver1">
                    ต้องการ <span id="approvalDisplay1"></span>อนุมัติ
                </span> <span style="padding-left: 10px;"
                              class="highlightPriceApporver2">ต้องการ<span id="approvalDisplay2"></span>อนุมัติ</span>
                <!--  <span style="padding-left: 10px;" class="highlightPriceApporver3">ต้องการ <span id="approvalDisplay3">
                  </span>อนุมัติ</span> <span style="padding-left: 10px;" class="highlightPriceApporver3">
                      ต้องการ <span id="approvalDisplay4"></span>อนุมัติ</span>-->
                <span style="padding-left: 10px;"
                      class="">Underline ราคาส่วนลดที่มากที่สุดในแต่ละรายการสินค้า</span>
            </div>
        </div>
        <div id="SaleCustomerDetailGrid" style="width: 100%; height: 270px; margin-top: 5px;">
        </div>
        <div>
            <div style="margin: 5px; vertical-align: middle;">
                <span style="width: 150px; display: inline-block;">Remark(สำหรับ sale & SC): </span>
                <textarea id="remark" cols="5" rows="3" style="width: 400px;"></textarea>
                <span id="realApprove" style="width: 60px;"></span>
            </div>
            <div style="margin: 5px; vertical-align: middle;">
                <span style="width: 150px; display: inline-block;">Reason From Approver(สำหรับ ผู้อนุมัติ): </span>
                <textarea id="remark2" cols="5" rows="3" style="width: 400px;"></textarea>
            </div>
        </div>
        <div id="divSendToApprover">
            <button id="btnSaveTodraft">
                Save To Draft
            </button>
            <button id="btnSendToApproval">
                Send To approval
            </button>
        </div>
        <div style="margin-top: 10px">
            <button id="btnPrint" style="display: none">
                Print
            </button>
        </div>
    </div>
    <div class="ui-layout-west" style="display: none;">
        <h3 class="ui-widget-header">
            Navigation
        </h3>
        <div class="ui-layout-content">
            <div id="accordion1" class="basic">
                <h3>
                    <a id="completeDocumentLink" href="#">Completed Document</a>
                </h3>
                <div id="completedDocument" style="width: 80%">
                </div>
            </div>
        </div>
    </div>
    <div id="dialog-message" title="Information!">
        <div style="margin-top: 12px;">
            <span class="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 50px 0;">
            </span>
            <div id="dialogMessageID">
            </div>
        </div>
    </div>
    <div id="dialog-parentAdd" title="ระบุชื่อร้านผู้แทนจำหน่าย!" style="display: none">
        <div id="Div2">
            <label>
                ชื่อร้านผู้แทนจำหน่าย :
            </label>
            <textarea id="txtParentHeader" rows="2" cols="50"> </textarea>
        </div>
    </div>
    <div id="dialog-creditTerm" title="กรุณาระบุ Credit term สำหรับแสดงราคาต่อกิโลของสายยางอ่อนใส!"
         style="display: none">
        <div id="Div3">
            <br />
            <input type="radio" id="Credit15" name="groupCreditTerm" value="15" checked="checked" />
            <label for="Credit15">
                ระยะเวลา 15 วัน
            </label>
            <br />
            <input type="radio" id="Credit30" name="groupCreditTerm" value="30" />
            <label for="Credit30">
                ระยะเวลา 30 วัน
            </label>
            <br />
            <input type="radio" id="Credit60" name="groupCreditTerm" value="60" />
            <label for="Credit60">
                ระยะเวลา 60 วัน
            </label>
        </div>
    </div>
    <div id="loadingScreen" style="vertical-align: middle; text-align: center">
    </div>
    <div id="DivNdpriceDetails" style="vertical-align: middle; text-align: center">
        <div id="NDPriceGrid" style="height: 300px; margin-bottom: 20px; padding-left: 10px;">
        </div>
    </div>
</body>
</html>
